package com.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.demo.common.ResultData;
import com.demo.config.HttpConfig;
import com.demo.util.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * GoogleReCaptcha
 *
 * @author wangfengchen
 */
@Slf4j
@RestController
@RequestMapping("/captcha")
public class GoogleReCaptchaController {

  @Value("${google.projectId:not_set}")
  private String projectId;
  @Value("${google.apiKey:not_set}")
  private String apiKey;
  @Value("${google.score:not_set}")
  private double score;
  @Autowired
  private HttpConfig httpConfig;


  /**
   * 校验验证码
   * <a href="https://cloud.google.com/recaptcha/docs/create-assessment-mobile?hl=zh-cn#create-assessment-REST%20API">https://cloud.google.com/recaptcha/docs/create-assessment-mobile?hl=zh-cn#create-assessment-REST%20API</a>
   *
   * @param token
   * @return
   */
  @GetMapping("/verify")
  public ResultData<Object> verify(@RequestParam String siteKey, @RequestParam String token) {
    String urlTemplate = "https://recaptchaenterprise.googleapis.com/v1/projects/{}/assessments?key={}";
    String url = StrUtil.format(urlTemplate, projectId, apiKey);
    String jsonTemplate = "{\n" +
        "  \"event\": {\n" +
        "    \"token\": \"{}\",\n" +
        "    \"siteKey\": \"{}\"\n" +
        "  }\n" +
        "}";
    String jsonData = StrUtil.format(jsonTemplate, token, siteKey);
    OkHttpClient okHttpClient = httpConfig.getOkHttpClient();
    String resp = OkHttpUtil.doPost(okHttpClient, url, jsonData);
    log.info("response = {}", resp);
    if (StringUtils.isBlank(resp)) {
      return ResultData.success(false);
    }
    JSONObject respObj = JSON.parseObject(resp);
    String tokenPropertiesResult = respObj.getString("tokenProperties");
    JSONObject tokenPropertiesResultObj = JSON.parseObject(tokenPropertiesResult);
    Boolean valid = tokenPropertiesResultObj.getBoolean("valid");
    if (!valid) {
      return ResultData.success(false);
    }
    String riskAnalysisResult = respObj.getString("riskAnalysis");
    JSONObject riskAnalysisObj = JSON.parseObject(riskAnalysisResult);
    double scoreResult = riskAnalysisObj.getDoubleValue("score");
    if (scoreResult >= score) {
      return ResultData.success(true);
    }
    return ResultData.success(false);
  }


}
